<?php
/* 
 * Emailing class that runs as cronjob
 * Available email types:
 *  a. DailyMail - a summary of today's event for the student on the next day
 * 
] */
class EmailCommand extends CConsoleCommand
{
    // Defines the mail type sent
    private $_mailType='DailyMail'; // Set default

    public function __construct()
    {
        if(isset($args[0]))
            $this->_mailType=$args[0];
        require_once (Yii::app()->basePath.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.'mailing_list.php');
        require_once (Yii::app()->basePath.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.'summaries.php');
        require_once (Yii::app()->basePath.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'grbac'.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.'Users.php');
    }
    public function run($args)
    {
        // Init a controller
        $controller = new CController('Site');
        // Create a custom email for each user in mailing list
        foreach($this->getRecipients() as $recipient)
        {
            // get user details 
            $user=Users::model()->findByPk($recipient['user_id']);
            
            $summaries = summaries::model()->findAll(
                array(  'select'=>'user_id, notes'
                        ,'condition'=>"note_date=:note_date"
                        ,'params'=>array(':note_date'=>date('Y-m-d',time()))
                        ,'order'=> 'user_id ASC'
                    )
            );
            
            $students = mailing_list::model()->findAll(
                array(  'condition'=>'assign_date = :assign_date'
                        ,'params'=>array(':assign_date' => date('Y-m-d',time()))
                )
            );
            foreach($students as $student)
                //echo $student['user_id']."\n";
                $student['notes']=$summaries[$student['user_id']]['notes'];
            //var_dump($studends['18']['notes']);

            // Render view
            //echo $user['id'].':'.$user['namef'].' '.$user['namel'].PHP_EOL;
            /*$emailText = $controller->renderInternal(
                                        Yii::app()->basePath.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'emails'.DIRECTORY_SEPARATOR.$this->_mailType.'.php'
                                        ,array('user'=>$user
                                            ,'summaries'=>$summaries
                                            ,'students'=>$students
                                            ),true);

            echo $emailText;*/
            //Send email
            //$this->sendEmail($user['email'],$this->getSubject(),$emailText);
        }  
    }
    
    private function sendEmail($to, $subject, $emailText) {
            $mailer = Yii::createComponent('application.extensions.mailer.EMailer');
            $mailer->IsSMTP();          // set mailer to use SMTP
            $mailer->SMTPAuth = true;   // turn on SMTP authentication
            $mailer->Host = 'smtp.gmail.com'; // specify main and backup server
            $mailer->SMTPSecure= 'ssl'; //  Used instead of TLS when only POP mail is selected
            $mailer->Port = 465;        //  Used instead of 587 when only POP mail is selected
            $mailer->Username = Yii::app()->params['emailAccount'];  // SMTP username, you could use your google apps address too.
            $mailer->Password = Yii::app()->params['emailPassword']; // SMTP password
            $mailer->From = Yii::app()->params['emailAccount'];
            $mailer->FromName = "מע' איילים";
            $mailer->CharSet = 'UTF-8';
            $mailer->IsHTML(true);
            $mailer->AddAddress($to);
            $mailer->Subject = $subject;
            $mailer->Body = $emailText;
            $mailer->Send();            
      }
    private function getRecipients()
    {
        switch($this->_mailType)
        {
            case 'DailyMail':
                $today = getdate(time());
                $offset = 60*60*24*($today['wday']==4?3:1);
                return mailing_list::model()->findAll('assign_date = :assign_date',array(':assign_date' => date('Y-m-d',time()+$offset)));
            default: return NULL;
        }
    }

    private function getSubject()
    {
        switch($this->_mailType)
        {
            case 'DailyMail': return 'דו"ח סיכום יומי '.date('d/m/Y',time());
        }
    }

}

?>
